using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Controls.Support;

namespace Sedna.Core.Controls
{
	/// <summary>
	/// Summary description for Container.
	/// </summary>
	public class Container : BaseContainer, IControlDataLoadAware
	{
		private ContainerConfiguration containerConfiguration;
	
		public override string ConfigurationId
		{
			get
			{
				return base.ConfigurationId;
			}
			set
			{
				configurationId = value;
			}
		}

		public override IConfiguration Configuration
		{
			get
			{
				return base.Configuration;
			}
			set
			{
				base.Configuration = value;
				this.containerConfiguration = (ContainerConfiguration)value;
			}
		}

		
		public Container(IConfiguration configuration): base (configuration)
		{
			containerConfiguration = (ContainerConfiguration)configuration;
		}
		public Container(){}

		protected override void CreateChildControls()
		{
			base.CreateControls (containerConfiguration.Layout, cellsArray);
		}

		protected override void OnInit(EventArgs e)
		{
			if (containerConfiguration == null)
			{
				containerConfiguration = (ContainerConfiguration)SpringContextFactory.GetContext().GetObject(configurationId);	
			}
			base.OnInit (e);
			EnsureChildControls();
		}


		protected override void Build()
		{
			base.Build();
			Build(containerConfiguration);
		}

//		protected override void SetupValidators()
//		{
//			EnsureChildControls();
//
//			for (int i = 0; i < controlsArray.Count; i ++)
//			{
//				if (controlsArray[i] is BaseControl)
//				{
//					continue;
//				}
//				IConfigurationAware configurationAware = controlsArray[i] as IConfigurationAware;
//				if (configurationAware == null)
//				{
//					continue;
//				}
//				if (configurationAware.Configuration == null)
//				{
//					configurationAware.Configuration = (IConfiguration)SpringContextFactory.GetContext().GetObject(configurationAware.ConfigurationId);
//				}
//				ControlUtil.SetupValidators(this, (Control)controlsArray[i], configurationAware.Configuration);
//			}
//		}

		private void Build(ContainerConfiguration containerConfiguration)
		{
			if (containerConfiguration.Cells == null) 
			{
				return;
			}
			for (int i = 0; i < containerConfiguration.Cells.Count; i++)
			{
				ILayoutCellConfiguration cellConfiguration = (ILayoutCellConfiguration) containerConfiguration.Cells[i];
				LayoutCell layoutCell = LayoutCell.BuildCell(cellConfiguration);
				cellsArray.Add(layoutCell);

				for (int j = 0; j < layoutCell.Controls.Count; j++)
				{
					controlsArray.Add(layoutCell.Controls[j]);
				}
			}
		}

	}
}
